package com.jlnk.stockdemo.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jlnk.stockdemo.R;
import com.jlnk.stockdemo.adapter.SpotAdapter;
import com.jlnk.stockdemo.bean.SpotListResponse;
import com.jlnk.stockdemo.viewmodel.SpotViewModel;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class SpotFragment extends Fragment {
    private static final String TAG = "SpotFragment";
    private SpotViewModel spotViewModel;
    private RecyclerView recyclerview_spot;
    private SpotAdapter spotAdapter;
    private List<SpotListResponse.Data.Spot> spotList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_spot, container, false);
        initView(view);
        return view;
    }

    private void initView(View view) {
        spotAdapter = new SpotAdapter(spotList);
        recyclerview_spot = view.findViewById(R.id.recyclerview_spot);
        recyclerview_spot.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerview_spot.setAdapter(spotAdapter);

        spotViewModel = new ViewModelProvider(this).get(SpotViewModel.class);
        spotViewModel.getSpotListLiveData().observe(getViewLifecycleOwner(), spots -> {
            this.spotList.clear();
            this.spotList.addAll(spots);
            spotAdapter.notifyDataSetChanged();
        });
        spotViewModel.fetchSpotList();
    }
}
